/*
 * Copyright (C) 2012 www.aboboo.com
 * 
 */
package com.aboboo.android.download;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import android.util.Log;
import android.os.Environment;

import com.aboboo.android.constant.AbobooConstant;

/**
 * 课件下载帮助类
 * 
 * @author fangepng
 * @version 1.0 2012-8-29
 */
public final class FileUtils {
	private String SDCardRoot;

	public FileUtils() {
		// 当前外部存储设备存储Aboboo课件的目录
		SDCardRoot = Environment.getExternalStorageDirectory()
				.getAbsolutePath()
				+ File.separator
				+ AbobooConstant.SDCARD_STORE_COURSEWARE_FILE_PATH
				+ File.separator;
	}

	/**
	 * 在SD卡上创建课件目录
	 * 
	 * @return
	 */
	public File createSDDir(String class1Dir, String class2Dir) {
		File dir = new File(SDCardRoot + class1Dir + File.separator + class2Dir
				+ File.separator);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	/**
	 * 在SD卡上创建课件文件
	 * 
	 * @param class1Dir
	 * @param class2Dir
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public File createSDFile(String class1Dir, String class2Dir, String fileName)
			throws IOException {
		File file = new File(SDCardRoot + class1Dir + File.separator
				+ class2Dir + File.separator + fileName);
		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();
		return file;
	}

	/**
	 * 取得用于保存课件的名称
	 * 
	 * @param downloadUrl
	 * @return
	 */
	public String getFileNameFromUrl(String downloadUrl, String fileName) {
		try {
			downloadUrl = URLDecoder.decode(
					URLDecoder.decode(downloadUrl, "UTF-8"), "UTF-8");
			return downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1);
		} catch (UnsupportedEncodingException e) {
			Log.i("解码JSON URl地址 出错", downloadUrl);
			return fileName + ".Q99";
		}
	}
}
